package com.web.advice;

import com.web.advice.exception.BusinessException;
import com.web.advice.exception.SystemException;
import com.web.common.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;



@RestControllerAdvice
public class ExceptionAdvice {
    private Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(BindException.class)
    public BaseResult handlerBindException(BindException e) {
        BaseResult BaseResult = new BaseResult();
        BaseResult.setState("-1");
        StringBuilder msg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(c ->
                msg.append(c.getDefaultMessage()).append(">"));
        BaseResult.setMessage(msg.substring(0, msg.length() - 1));
        return BaseResult;
    }

    @ExceptionHandler(SystemException.class)
    public ResponseEntity myExceptionHandler(Exception e) {
        logger.error("异常：", e);
        return ResponseEntity.internalServerError().body(createE(new SystemException("系统内部异常，请联系系统管理员。")));
    }


    @ExceptionHandler(BusinessException.class)
    public ResponseEntity businessExceptionHandler(Exception e) {
        logger.error("业务控制：", e);
        return ResponseEntity.internalServerError().body(createBusiE(e));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity exceptionHandler(Exception e) {
        logger.error("异常：", e);
        return ResponseEntity.internalServerError().body(createE(new SystemException("操作失败")));
    }

    public BaseResult createE(Exception e) {
        BaseResult BaseResult = new BaseResult();
        BaseResult.setState("-2");
        BaseResult.setMessage(e.getMessage());
        return BaseResult;
    }

    public BaseResult createBusiE(Exception e) {
        BaseResult BaseResult = new BaseResult();
        BaseResult.setState("-1");
        BaseResult.setMessage(e.getMessage());
        return BaseResult;
    }
}
